package com.android.topview.watermelon.util

private val NUMBERS = arrayOf(
    "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"
)

private val IUNIT = arrayOf(
    "元", "拾", "佰", "仟", "万", "拾", "佰",
    "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟"
)

private val DUNIT = arrayOf("角", "分")

fun String.toChinese(): String {
    var integerStr: String
    val decimalStr: String

    when {
        this.indexOf(".") > 0 -> {
            integerStr = this.substring(0, this.indexOf("."))
            decimalStr = this.substring(this.indexOf(".") + 1)
        }
        this.indexOf(".") == 0 -> {
            integerStr = ""
            decimalStr = this.substring(1)
        }
        else -> {
            integerStr = this
            decimalStr = ""
        }
    }

    if (integerStr != "") {
        integerStr = integerStr.toLong().toString()
        if (integerStr == "0") {
            integerStr = ""
        }
    }

    if (integerStr.length > IUNIT.size) {
        throw NumberFormatException()
    }
    val integers = toArray(integerStr)
    val isMust5 = isMust5(integerStr)
    val decimals = toArray(decimalStr)
    return getChineseInteger(integers, isMust5) + getChineseDecimal(decimals)
}

private fun toArray(number: String): IntArray {
    val array = IntArray(number.length)
    for (i in number.indices) {
        array[i] = number.substring(i, i + 1).toInt()
    }
    return array
}

private fun getChineseInteger(integers: IntArray, isMust5: Boolean): String {
    val chineseInteger = StringBuffer("")
    val length = integers.size
    for (i in 0 until length) {
        var key = ""
        if (integers[i] == 0) {
            if (length - i == 13)
                key = IUNIT[4] else if (length - i == 9)
                key = IUNIT[8] else if (length - i == 5 && isMust5)
                key = IUNIT[4] else if (length - i == 1)
                key = IUNIT[0]
            if (length - i > 1 && integers[i + 1] != 0) key += NUMBERS[0]
        }
        chineseInteger.append(if (integers[i] == 0) key else NUMBERS[integers[i]] + IUNIT[length - i - 1])
    }
    return chineseInteger.toString()
}

private fun getChineseDecimal(decimals: IntArray): String {
    val chineseDecimal = StringBuffer("")
    for (i in decimals.indices) {
        if (i == 2) break
        chineseDecimal.append(if (decimals[i] == 0) "" else NUMBERS[decimals[i]] + DUNIT[i])
    }
    return chineseDecimal.toString()
}

private fun isMust5(integerStr: String): Boolean {
    val length = integerStr.length
    return if (length > 4) {
        val subInteger: String = if (length > 8) {
            integerStr.substring(length - 8, length - 4)
        } else {
            integerStr.substring(0, length - 4)
        }
        subInteger.toInt() > 0
    } else {
        false
    }
}

